<template>
  <view class="wrap">
    <view class="result-box">
      <view class="result-main">
        <view class="desc">
          <view class="unbind-box" @tap="unbindDevice">
            <text class="unbind-text">解绑设备</text>
          </view>
          <image
            class="desc-img"
            src="https://ainengli.hzjrsw.com/jkhx/common/test-finish.png"
            mode="scaleToFill"
          />
          <text class="desc-text">测量结束，请查看测量结果</text>
        </view>
        <view class="measure-list">
          <view class="measure-item">
            <text class="name">测量指标</text>
            <text class="value">{{ matchName() }}</text>
          </view>
          <view class="measure-item">
            <text class="name">测量时间</text>
            <text class="value">{{ measureData.measureTime }}</text>
          </view>
          <!-- 血糖 -->
          <view
            class="measure-item"
            @tap="bloodSugerRange"
            v-if="measureData.valueType === 'CTRL' || measureData.valueType === 'BLOOD'"
          >
            <text class="name">测量时段</text>
            <view class="measure-range">
              <text class="value">{{ rangeName }}</text>
              <image
                class="select-icon"
                src="https://ainengli.hzjrsw.com/jkhx/common/form-arrow-right.png"
                mode="scaleToFill"
              />
            </view>
          </view>
          <!--  -->
          <view class="measure-item">
            <text class="name">测量结果</text>
            <text class="value">{{ measureData.value }}{{ measureData.currUnit }}</text>
          </view>
        </view>
      </view>
      <view
        class="result-footer"
        @tap="saveBloodSugar"
        v-if="measureData.valueType === 'CTRL' || measureData.valueType === 'BLOOD'"
      >
        <text>保存并查看更多{{ matchName() }}数据</text>
      </view>
      <view class="result-footer" v-else @tap="goDetail">
        <text>查看更多{{ matchName() }}数据</text>
      </view>
    </view>

    <up-popup
      :show="isRangeVisible"
      :round="16"
      mode="bottom"
      closeable
      @close="isRangeVisible = false"
    >
      <view class="title">测量时段</view>
      <view class="lists">
        <view
          v-for="(item, index) in rangeList"
          :key="index"
          class="item"
          @tap="selectRangeHandle(item)"
        >
          <text class="name">{{ item.name }}</text>
        </view>
      </view>
    </up-popup>
  </view>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { saveReport, unbindEquipment } from './equipment.api'
import type { equipmentSaveModel, detailData } from './equipmentModel'

const isRangeVisible = ref<boolean>(false)
const rangeName = ref<string>('')
const rangeValue = ref<string>('')
const deviceNo = ref('')
const empiId = ref('')

const rangeList = reactive([
  {
    name: '空腹',
    value: 'empty_stomach'
  },
  {
    name: '早餐后2h',
    value: 'breakfast_after_2'
  },
  {
    name: '午餐前',
    value: 'lunch_before'
  },
  {
    name: '午餐后2h',
    value: 'lunch_after_2'
  },
  {
    name: '晚餐前',
    value: 'dinner_before'
  },
  {
    name: '晚餐后2h',
    value: 'dinner_after_2'
  },
  {
    name: '睡前',
    value: 'sleep_before'
  }
])

interface measureDataModel {
  measureTime: string
  value: string
  currSn: string
  currUnit: string
  valueType: string
}

const measureData = ref<measureDataModel>({
  measureTime: '',
  value: '',
  currSn: '',
  currUnit: '',
  valueType: ''
})

onShow(() => {
  if (uni.hideHomeButton) {
    uni.hideHomeButton()
  }
})

onLoad((option: any) => {
  const options = JSON.parse(decodeURIComponent(option.data))
  uni.setNavigationBarTitle({
    title: option && option.name == 'analysis' ? '微策三合一分析仪' : ''
  })
  console.log(options)
  deviceNo.value = options.deviceId
  empiId.value = options.measureEmpi
  measureData.value = options
  if (options.measureTime) {
    getBloodSugarTime(measureData.value.measureTime)
  }

  if (measureData.value.valueType == 'BLOOD_KET' || measureData.value.valueType == 'CTRL_KET') {
    saveMeasureData('blood_ketone_data', 'blood_ketone')
  }

  if (measureData.value.valueType == 'BLOOD_UA' || measureData.value.valueType == 'CTRL_UA') {
    saveMeasureData('uric_acid_data', 'uric_acid')
  }
})

const bloodSugerRange = () => {
  isRangeVisible.value = true
}

const selectRangeHandle = (data: any) => {
  isRangeVisible.value = false
  rangeName.value = data.name
  rangeValue.value = data.value
}

// 解绑
const unbindDevice = () => {
  uni.showModal({
    title: '解除绑定',
    cancelColor: '#666',
    confirmColor: '#00D1B6',
    content: '确定要解除绑定微策三合一分析仪吗?',
    success: (res) => {
      if (res.confirm) {
        unbindEquipment(deviceNo.value).then(() => {
          uni.showToast({
            title: '解绑成功',
            duration: 800
          })

          setTimeout(() => {
            uni.redirectTo({
              url: '/module/src/pages/myEquipment/index'
            })
          }, 1000)
        })
      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    }
  })
}

//  血糖的保存
const saveBloodSugar = () => {
  console.log(empiId.value)
  const data: detailData = {
    empi: empiId.value,
    indicatorKey: rangeValue.value,
    indicatorValue: measureData.value.value,
    parentKey: 'blood_sugar'
  }
  const datas: equipmentSaveModel = {
    details: [data],
    report: {
      reportSource: 'WEICE',
      empi: empiId.value,
      checkTime: measureData.value.measureTime,
      indicatorKey: 'blood_sugar'
    }
  }

  uni.showLoading({
    title: '保存中'
  })
  saveReport(datas).then((res: any) => {
    uni.hideLoading()
    uni.showToast({
      title: '保存成功',
      duration: 1000
    })

    setTimeout(() => {
      uni.redirectTo({
        url: `/module/src/pages/healthPortrait/healthDataRecord?type=blood_sugar?empi=${empiId.value}`
      })
    }, 500)
  })
}

// 血酮/ 尿酸保存
const saveMeasureData = (key: string, parentKey: string) => {
  const data: detailData = {
    empi: empiId.value,
    indicatorKey: key,
    indicatorValue: measureData.value.value,
    parentKey: parentKey
  }

  const datas: equipmentSaveModel = {
    details: [data],
    report: {
      reportSource: 'WEICE',
      empi: empiId.value,
      checkTime: measureData.value.measureTime,
      indicatorKey: parentKey
    }
  }

  uni.showLoading({
    title: '加载中'
  })
  saveReport(datas).then(() => {
    uni.hideLoading()
  })
}

// 跳转
const goDetail = () => {
  if (matchName() == '尿酸') {
    uni.navigateTo({
      url: '/module/src/pages/healthPortrait/healthDataRecord?type=uric_acid'
    })
  } else if (matchName() == '血酮') {
    uni.navigateTo({
      url: '/module/src/pages/healthPortrait/healthDataRecord?ttype=blood_ketone'
    })
  }
}

const matchName = () => {
  switch (measureData.value.valueType) {
    case 'BLOOD':
      return '血糖'
    case 'CTRL':
      return '血糖'
    case 'BLOOD_KET':
      return '血酮'
    case 'CTRL_KET':
      return '血酮'
    case 'BLOOD_UA':
      return '尿酸'
    case 'CTRL_UA':
      return '尿酸'
    default:
      return '血糖'
  }
}

// 血糖-- 根据当前时间匹配时间段标签
const getBloodSugarTime = (time: string) => {
  const date = new Date(time)
  const times = date.getTime()
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  switch (true) {
    case times >= getTimestamp(year, month, day) &&
      times <= getTimestamp(year, month, day, 7, 59, 59):
      rangeName.value = rangeList[0].name
      rangeValue.value = rangeList[0].value
      break
    case times >= getTimestamp(year, month, day, 8, 0, 0) &&
      times <= getTimestamp(year, month, day, 9, 59, 59):
      rangeName.value = rangeList[1].name
      rangeValue.value = rangeList[1].value
      break
    case times >= getTimestamp(year, month, day, 10, 0, 0) &&
      times <= getTimestamp(year, month, day, 11, 59, 59):
      rangeName.value = rangeList[2].name
      rangeValue.value = rangeList[2].value
      break
    case times >= getTimestamp(year, month, day, 12, 0, 0) &&
      times <= getTimestamp(year, month, day, 14, 59, 59):
      rangeName.value = rangeList[3].name
      rangeValue.value = rangeList[3].value
      break
    case times >= getTimestamp(year, month, day, 15, 0, 0) &&
      times <= getTimestamp(year, month, day, 17, 59, 59):
      rangeName.value = rangeList[4].name
      rangeValue.value = rangeList[4].value
      break
    case times >= getTimestamp(year, month, day, 18, 0, 0) &&
      times <= getTimestamp(year, month, day, 20, 59, 59):
      rangeName.value = rangeList[5].name
      rangeValue.value = rangeList[5].value
      break
    case times >= getTimestamp(year, month, day, 21, 0, 0) &&
      times <= getTimestamp(year, month, day, 23, 59, 59):
      rangeName.value = rangeList[6].name
      rangeValue.value = rangeList[6].value
      break
    default:
      rangeName.value = rangeList[0].name
      rangeValue.value = rangeList[0].value
      break
  }
}

const getTimestamp = (year: any, month: any, day: any, hour = 0, minute = 0, second = 0) => {
  const date = new Date(year, month - 1, day, hour, minute, second)
  return date.getTime()
}
</script>
<style lang="scss" scoped>
.wrap {
  min-height: 100vh;
  padding: 26rpx 32rpx 24rpx;
  background-color: #fff;
}

.result-box {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  width: 100%;
  height: calc(100vh - 92rpx);
}

.desc {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  height: 380rpx;
  margin-bottom: 66rpx;

  .unbind-box {
    width: 100%;
    height: 50rpx;
    text-align: right;

    .unbind-text {
      display: inline-block;
      width: 144rpx;
      height: 50rpx;
      font-size: 24rpx;
      font-weight: 700;
      line-height: 50rpx;
      color: #222;
      text-align: center;
      background: #fff;
      border: 1rpx solid #e5e6eb;
      border-radius: 28rpx;
    }
  }

  .desc-img {
    width: 131rpx;
    height: 131rpx;
    margin-top: 52rpx;
    margin-bottom: 54rpx;
  }

  .desc-text {
    font-size: 40rpx;
    font-weight: 700;
    color: #1d2129;
  }
}

.measure-list {
  .measure-item {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 108rpx;
    padding: 0 32rpx;
    margin-bottom: 24rpx;
    background: #fafafa;
    border: 1rpx solid #e5e6eb;
    border-radius: 16rpx;

    .name {
      font-size: 30rpx;
      font-weight: 700;
      color: #222;
    }

    .value {
      font-size: 30rpx;
      font-weight: 400;
      color: #222;
    }
  }
}

.measure-range {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-left: 8rpx;
}

.select-icon {
  width: 32rpx;
  height: 32rpx;
}

.result-footer {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 88rpx;
  font-size: 32rpx;
  font-weight: 700;
  color: #fff;
  background: #00d1b6;
  border-radius: 44rpx;
}

.u-popup {
  .title {
    height: 108rpx;
    font-size: 32rpx;
    font-weight: 700;
    line-height: 108rpx;
    color: #222;
    text-align: center;
    border-bottom: 1rpx solid #e5e6eb;
  }

  .lists {
    max-height: 800rpx;
    padding: 32rpx;
    overflow: auto;
    background: #fff;

    .item {
      display: flex;
      align-items: center;
      width: 100%;
      height: 96rpx;
      padding-left: 24rpx;
      margin-bottom: 24rpx;
      text-align: center;
      background: #fafafa;
      border-radius: 8rpx;

      .name {
        font-size: 30rpx;
        font-weight: 500;
        color: #222;
      }
    }
  }
}
</style>
